//
//  TempFileExt.swift
//  ANOA
//
//  Created by 邱仙凯 on 2023/7/12.
//  Copyright © 2023 zwb. All rights reserved.
//

import UIKit

// MARK: 附件相关
extension ConfigMenuForm:KSImageUtilDelegate {
    // 附件加载
    func fetchMainFile(finish:@escaping(()->())) {
        // 如果模板里有附件类型 则先去加载附件
        let ftA = self.mainHandler.filter { $0.temp!.field_type == TemplateType.file.rawValue }
        if ftA.count > 0 {
            // 创建调度组
            let workingGroupMain = DispatchGroup()
            for yy in 0..<self.mainHandler.count {
                let tempOne = self.mainHandler[yy].temp!
                if tempOne.field_type == TemplateType.file.rawValue {
                    // 入组
                    workingGroupMain.enter()
                    queryPicture_temp(templateDic:self.templateDic,module_id:self.rootTemp.module_id.unwrap,vouid: any2Str(self.main[TKey.id_key]),item: tempOne) { items in
                        var imggA = [VideoImg]()
                        
                        let workingGroupDet = DispatchGroup()
                        
                        for item in items {
                            var ttt:SourType = .file
                            if item.zPicUrl.unwrap.contains("png") || item.zPicUrl.unwrap.contains("jpg") ||
                                item.zPicUrl.unwrap.contains("jpeg") {
                                ttt = .image
                            }
                            if item.zPicUrl.unwrap.contains("mp4") {
                                ttt = .video
                            }
                            var one = VideoImg(type: ttt, idkey: item.idKey.unwrap, url: configURLOK(latter: item.zPicUrl.unwrap), name: item.zPicName.unwrap, clipName: item.clipName, isComplete: (item.complete == 1))
                            if ttt == .image {
                                //                                one.image = getPicture(url: one.url.unwrap)
                                
                                
                                workingGroupDet.enter()
                                getImageCacheOrnet(url: one.url.unwrap, clipName: one.clipName.unwrap, ignoreNet: true, imgBackClo: { vimg in
                                    one.image = vimg.image
                                    imggA.append(one)
                                    workingGroupDet.leave()
                                })
                                
                                
                            } else if ttt == .video {
                                // 取本地磁盘视频的封面
                                if item.clipName.unwrap != "" {
                                    one.image = FileCacheTool.getVideoThumbnail(fileName: item.clipName!)
                                }
                                imggA.append(one)
                            } else {
                                // 文件
                                one.name = one.name?.removingPercentEncoding
                                one.clipName = one.clipName?.removingPercentEncoding
                                imggA.append(one)
                            }
                            
                        }
                        
                        
                        // 调度组里的任务都执行完毕
                        workingGroupDet.notify(queue: .main) {
                            self.mainHandler[yy].imgArray = imggA
                            // 出组
                            workingGroupMain.leave()
                        }
                        
                    }
                }
                
            }
            
            // 调度组里的任务都执行完毕
            workingGroupMain.notify(queue: .main) {
                finish()
            }
            
        } else {
            finish()
        }
    }
    func fetchMainFile_draft(finish:@escaping(()->())) {
        // 如果模板里有附件类型 则先去加载附件
        let ftA = self.mainHandler.filter { $0.temp!.field_type == TemplateType.file.rawValue }
        if ftA.count > 0 {
            // 创建调度组
            let workingGroupMain = DispatchGroup()
            for yy in 0..<self.mainHandler.count {
                let tempOne = self.mainHandler[yy].temp!
                if tempOne.field_type == TemplateType.file.rawValue {
                    let filePara = tempOne.field_nm.unwrap + "#file_dic"
                    if let fDic = self.main[filePara] {
                        // 入组
                        workingGroupMain.enter()
                        dicArr2imgArr(fDic:fDic) { imggA in
                            self.mainHandler[yy].imgArray = imggA
                            // 出组
                            workingGroupMain.leave()
                        }
                        
                    }

                }
                
            }
            
            // 调度组里的任务都执行完毕
            workingGroupMain.notify(queue: .main) {
                finish()
            }
            
        } else {
            finish()
        }
    }

    func fetchDetailFile_draft(finish:@escaping(()->())) {
        // 如果模板里有附件类型 则先去加载附件
        // 创建调度组
        
        
   
        var detailSectionCount = 1
        if rootTemp.multiDetailsParams.count > 0 {
            detailSectionCount = rootTemp.multiDetailsParams.count
        }
        var needGetFile = false
        let workingGroup = DispatchGroup()
        for u in 0..<detailSectionCount {
            
            let xxxA = self.detHandler[u].filter { $0.temp.filter{ $0.field_type == TemplateType.file.rawValue }.count > 0 }
            if xxxA.count > 0 {
               
                needGetFile = true
                for xxx in 0..<self.detHandler[u].count {
                    let detO = self.detHandler[u][xxx].temp
                    let dicO = self.detHandler[u][xxx].dic
                    for yy in 0..<detO.count {
                        let tempOne = detO[yy]
                        
                        if tempOne.field_type == TemplateType.file.rawValue {
                       
                            let filePara = tempOne.field_nm.unwrap + "#file_dic"
                            if let fDic = dicO[filePara] {
                                // 入组
                                workingGroup.enter()
                                dicArr2imgArr(fDic:fDic) { imggA in
                                    self.detHandler[u][xxx].imgArray = imggA
                                    // 出组
                                    workingGroup.leave()
                                }
                            }
                        }
                    }
                }
            }
        }
        
 
        if needGetFile {
            // 调度组里的任务都执行完毕
            workingGroup.notify(queue: .main) {
                finish()
            }
        } else {
            finish()
        }
        
        
    }
    func fetchDetailFile(finish:@escaping(()->())) {
        // 如果模板里有附件类型 则先去加载附件
        // 创建调度组
        
        
        
        // 细表判空校验
        var detailSectionCount = 1
        if rootTemp.multiDetailsParams.count > 0 {
            detailSectionCount = rootTemp.multiDetailsParams.count
        }
        var needGetFile = false
        let workingGroupMain = DispatchGroup()
        for u in 0..<detailSectionCount {
            
            let xxxA = self.detHandler[u].filter { $0.temp.filter{ $0.field_type == TemplateType.file.rawValue }.count > 0 }
            if xxxA.count > 0 {
               
                needGetFile = true
                for xxx in 0..<self.detHandler[u].count {
                    let detO = self.detHandler[u][xxx].temp
                    let dicO = self.detHandler[u][xxx].dic
                    for yy in 0..<detO.count {
                        let tempOne = detO[yy]
                        
                        if tempOne.field_type == TemplateType.file.rawValue {
                            // 入组
                            workingGroupMain.enter()
                            queryPicture_temp(templateDic:self.templateDic,module_id:self.rootTemp.module_id.unwrap,vouid: any2Str(dicO[TKey.id_key]),item: tempOne) { items in
                                
                                 
                                
                                
                                let workingGroupDet = DispatchGroup()
                                
                                var imggA = [VideoImg]()
                                for item in items {
                                    var ttt:SourType = .file
                                    if item.zPicUrl.unwrap.contains("png") || item.zPicUrl.unwrap.contains("jpg") ||
                                        item.zPicUrl.unwrap.contains("jpeg") {
                                        ttt = .image
                                    }
                                    if item.zPicUrl.unwrap.contains("mp4") {
                                        ttt = .video
                                    }
                                    var one = VideoImg(type: ttt, idkey: item.idKey.unwrap, url: configURLOK(latter: item.zPicUrl.unwrap), name: item.zPicName.unwrap)
                                    if ttt == .image {
                                        workingGroupDet.enter()
                                        getImageCacheOrnet(url: one.url.unwrap, ignoreNet: true, imgBackClo: { vimg in
                                            one.image = vimg.image
                                            workingGroupDet.leave()
                                        })
                                        // 旧的没缓存的获取图片弃用
                                        //                                    getPicture(url: one.url.unwrap)
                                    }
                                    imggA.append(one)
                                }
                                
                                // 调度组里的任务都执行完毕
                                workingGroupDet.notify(queue: .main) {
                                    self.detHandler[u][xxx].imgArray = imggA
                                    // 出组
                                    workingGroupMain.leave()
                                }
                            }
                        }
                    }
                }
            }
        }
    

        if needGetFile {
            // 调度组里的任务都执行完毕
            workingGroupMain.notify(queue: .main) {
                finish()
            }
        } else {
            finish()
        }
    }
    
    
    // 字典数组  获取  图片数组
    func dicArr2imgArr(fDic:Any,backClo:@escaping(([VideoImg])->())) {
        
          var xcDic = [[String: Any]]()
           
          let trimmedString = any2Str(fDic).trimmingCharacters(in: CharacterSet.whitespacesAndNewlines.union(.init(charactersIn: "\"\"")))
             if let jsonData = trimmedString.data(using: .utf8) {
                 do {

                     // 使用 JSONSerialization 解析 Data 为字典数组
                         if let jsonArray = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.mutableContainers) as? [[String: Any]] {
                         
                             xcDic = jsonArray
                         }
                     
         
                 } catch {
                     print("Error deserializing JSON: \(error.localizedDescription)")
                 }
             }
          
        
          
        
              var imggA = [VideoImg]()
              
              let workingGroupDet = DispatchGroup()
              
              for item in xcDic {
                  var ttt:SourType = .file
                  let filePath = any2Str(item["filePath"])
                  if filePath.contains("png") || filePath.contains("jpg") ||
                      filePath.contains("jpeg") {
                      ttt = .image
                  }
                  if filePath.contains("mp4") {
                      ttt = .video
                  }
                  
                  let urlD = configURLOK(latter: filePath)
                  KSLog("urlD2d")
                  KSLog(urlD)
                  var one = VideoImg(type: ttt, idkey: "", url:urlD , name: any2Str(item["fileName"]), clipName: any2Str(item["clip_name"]))
                  
                  if ttt == .file {
                      do {
                          let fileData = try NSData(contentsOf: URL(string: urlD)!, options: .dataReadingMapped)
                          one.data = fileData as Data
                      } catch {
                          return
                      }
                  }
              
                  
                  if ttt == .image {
                      //                                one.image = getPicture(url: one.url.unwrap)
                      
                      workingGroupDet.enter()
                      getImageCacheOrnet(url: one.url.unwrap, imgBackClo: { vimg in
                          one.image = vimg.image
                          imggA.append(one)
                          workingGroupDet.leave()
                      })
                                            
                  } else {
                      if ttt == .video {
                          // 取本地磁盘视频的封面
                          if one.clipName.unwrap != "" {
                              one.image = FileCacheTool.getVideoThumbnail(fileName: one.clipName!)
                          }
                      }
                      
                      imggA.append(one)
                  }
              }
              
              
              // 调度组里的任务都执行完毕
              workingGroupDet.notify(queue: .main) {
                  backClo(imggA)
              }
              
          
          

    }
    
    // 附件显示
    
    func addImages(_ util:KSImageSelectUtil, imgvideos:[VideoImg]) {
        if let index = self.mainHandler.getIndexFor({ onex in
            onex.item?.tagx == util.tagx
        }) {
            var tts = imgvideos
            // 把名称  data 处理好
            for i in 0..<tts.count {
                let fdata = resetImgSize(sourceImage: tts[i].image!, maxImageLenght: filemaxImageLenght, maxSizeKB: filemaxSizeKB)
                tts[i].data = fdata
                let fname = getAttachName(i: i)
                if tts[i].type == .image {
                    tts[i].name = "\(fname).jpg"
                } else if tts[i].type == .video {
                    tts[i].name = "\(fname).mp4"
                } else {
                    tts[i].name = "\(fname).pdf"
                }
               
            }
            
            
            self.mainHandler[index].imgArray += tts
        }
        
        
    }
    func  addFiles(_ util: KSImageSelectUtil, files: [VideoImg]) {
        if let index = self.mainHandler.getIndexFor({ onex in
            onex.item?.tagx == util.tagx
        }) {
            self.mainHandler[index].imgArray += files
        } else {
            // 否则就是细表来的
            
            
            
            
        }
    }
    func deleteImage(_ util: KSImageSelectUtil, index: Int) {
        
  
        
        alertUtil(self, title: "确认删除", operateS: [nameAction(name: "确定", action: { _ in
            if let ind = self.mainHandler.getIndexFor({ onex in
                onex.item?.tagx == util.tagx
            }) { // 新图片方式
                let one = self.mainHandler[ind].imgArray[index]
                let temp = self.mainHandler[ind].temp!
                if one.idkey.unwrap.isEmpty {
                    self.mainHandler[ind].imgArray.remove(at: index)
                    util.deleteLocalImg(tag: index)
                } else {
                    
                    deleImage_temp(templateDic:self.templateDic,idkey:one.idkey.unwrap,vou_id: any2Str(self.main[TKey.id_key]),module_id: self.rootTemp.module_id.unwrap,temp: temp) {
                        self.mainHandler[ind].imgArray.remove(at: index)
                        util.deleteLocalImg(tag: index)
                    }
                }
            }
            
            
        })])
        
        
        
    }
}
